package com.hmall.search.web;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.PageDTO;

import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDOC;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    public ItemClient itemClient;

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private SearchService searchService;

    @GetMapping("/es/{page}/{size}")
    public String bulkImport(@PathVariable("page") Integer page, @PathVariable("size") Integer size ) {
        try {
            PageDTO<Item> pageDTO = itemClient.list(page, size);
            List<Item> list = pageDTO.getList();
            BulkRequest request = new BulkRequest();
            for (Item item : list) {
                ItemDOC itemDOC = new ItemDOC(item);
                request.add(new IndexRequest("hmall")
                        .id(itemDOC.getId().toString())
                        .source(JSON.toJSONString(itemDOC), XContentType.JSON));
            }
            client.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "导入成功";
    }

    @GetMapping("/suggestion")
    public List<String> suggestion(@RequestParam("key") String key) {
        return searchService.suggestion(key);

    }

    @PostMapping("/list")
    public PageDTO<ItemDOC> list(@RequestBody RequestParams params) {
        return searchService.list(params);
    }

    @PostMapping("/filters")
    public Map<String, List<String>> filters(@RequestBody RequestParams params) {
        return searchService.filters(params);
    }

}
